<template>
	<ElConfigProvider
		:locale="zhCn"
		:size="size"
		:button="{
			autoInsertSpace: true
		}"
	>
		<div id="ref-app">
			<RouterView v-slot="{ Component }">
				<transition name="fade">
					<component :is="Component" />
				</transition>
			</RouterView>
		</div>
	</ElConfigProvider>
</template>

<script setup name="App">
import zhCn from 'element-plus/dist/locale/zh-cn.mjs';
import { whiteRouter } from '@/router/whiteRouter';
import { useWindowSize, useIdle } from '@vueuse/core';
import { USEIDLETIMEl } from '@/config';

/************************************************监听窗口大小***********************************/
const { width } = useWindowSize();
const size = computed(() => (width.value > 1024 ? 'default' : 'small'));

/************************************************页面无操作30分钟自动退出功能***********************************/
if (USEIDLETIMEl) {
	const { idle } = useIdle((window?.__config_?.USEIDLETIMEl ?? 30) * 60 * 1000),
		$route = useRoute();
	watch(idle, (curr) => {
		if (curr && !whiteRouter($route.path) && $store.user.token) {
			$store.user.LogOut().then(() => {
				$router.push({
					path: '/login',
					query: {
						redirect: $route.fullPath
					}
				});
			});
		}
	});
}

/************************************************关闭窗口自动退出功能***********************************/
let beforeUnload_time;
function handleBeforeUnload() {
	beforeUnload_time = new Date().getTime();
}
function handlerUnload() {
	const gap_time = new Date().getTime() - beforeUnload_time;
	// gap_time 表示 beforeUnload 与 unload 执行的时间差，设置为50ms左右较为合适,
	// 10~50ms区间都行，此处设置为50ms，是为了保证大概率触发，不建议设置小于10ms，经实测，多数关闭浏览器情况下，gap_time < 10 都是不成立的
	if (gap_time <= 5) {
		$store.user.LogOut();
		$store.user.LogOutSET();
	}
}
// dom创建完成
onMounted(() => {
	// 关闭窗口自动退出功能
	window.addEventListener('beforeunload', () => handleBeforeUnload());
	window.addEventListener('unload', () => handlerUnload());
});
// 组件销毁
onUnmounted(() => {
	window.removeEventListener('beforeunload', () => handleBeforeUnload());
	window.removeEventListener('unload', () => handlerUnload());
});
</script>

<style lang="scss">
#ref-app {
	width: 100%;
	height: 100%;
	overflow: hidden;
	background-color: var(--el-bg-color);
}
</style>
